package com.s666.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录角色权限相关
 * @author lijin
 */
@Configuration
@EnableWebSecurity
public class SecurityCfg extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customAuthenticationDetailsSource")
    private AuthenticationDetailsSource<HttpServletRequest, CustomWebAuthenticationDetails> authenticationDetailsSource;

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()  // 定义哪些URL需要被保护、哪些不需要被保护
                //.antMatchers("/", "/verify", "/home","/static/*").permitAll()
                .antMatchers("/hutool/post","/test/*", "/**", "/verify", "/home","/static/*").permitAll()
                .anyRequest().authenticated()   // 任何请求,登录后可以访问
                .and()
            .formLogin()    //  定义当需要用户登录时候，转到的登录页面。
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .permitAll()
              //  .failureUrl("/login/error")
                .authenticationDetailsSource(authenticationDetailsSource)
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
            .logout()
                .permitAll()
            // 关闭csrf防护, 用于测试方便，生产上是h5页面要加上
            .and() .csrf().disable();
    }
    @Autowired
    @Qualifier("webUserDetailsService")
    UserDetailsService userDetailsService;
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
        //auth.userDetailsService(userDetailsService);
    }
    /**
     * 解决静态资源被拦截的问题(这个静态常用nginx转发,故也不是必须的)
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/static/**");
    }
/*
    // 使用内存帐号, 可用于测试
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin").password("123456").roles("USER");
    }
*/
}
/*
//自定义过滤器，把资源配置存放到数据库中
        .addFilterBefore(filter(),FilterSecurityInterceptor.class)
        .exceptionHandling()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login?logout")
        .invalidateHttpSession(true)
        .deleteCookies("remember-me")
        .and()
        .rememberMe()
        .tokenRepository(tokenRepository())
        .tokenValiditySeconds(1209600)//默认2周
        .rememberMeCookieName("remember-me")
        .userDetailsService(userDetailsService)
        .rememberMeParameter("remember-me");
*/
